//
//  NSArray+Addition.m
//  Project
//
//  Created by  CarlsonLee on 2018/12/8.
//  Copyright © 2018年 YANJING. All rights reserved.
//

#import "NSArray+Addition.h"
#import <objc/runtime.h>

@implementation NSArray (Addition)

+ (void)load {
    [super load];
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [objc_getClass("__NSArray0") gel_systemSelector:@selector(objectAtIndex:) swizzledSelector:@selector(gel_objectAtIndex0:) error:nil];
        [objc_getClass("__NSArrayI") gel_systemSelector:@selector(objectAtIndex:) swizzledSelector:@selector(gel_objectAtIndex:) error:nil];
        [objc_getClass("__NSSingleObjectArrayI") gel_systemSelector:@selector(objectAtIndex:) swizzledSelector:@selector(gel_objectAtIndexS:) error:nil];
        [objc_getClass("__NSArrayI") gel_systemSelector:@selector(objectAtIndexedSubscript:) swizzledSelector:@selector(gel_objectAtIndexedSubscript:) error:nil];
    });
}

- (id)gel_objectAtIndex:(NSUInteger)index {
    if(index<self.count){
        return [self gel_objectAtIndex:index];
    }else{
        NSLog(@"数组已越界objectAtIndex = %ld  count = %ld", index, self.count);
        return nil;
    }
}

- (id)gel_objectAtIndex0:(NSUInteger)index {
    if(index<self.count){
        return [self gel_objectAtIndex0:index];
    }else{
        NSLog(@"数组已越界objectAtIndex = %ld  count = %ld", index, self.count);
        return nil;
    }
}

- (id)gel_objectAtIndexS:(NSUInteger)index {
    if(index<self.count){
        return [self gel_objectAtIndexS:index];
    }else{
        NSLog(@"数组已越界objectAtIndex = %ld  count = %ld", index, self.count);
        return nil;
    }
}

- (id)gel_objectAtIndexedSubscript:(NSUInteger)index {
    if(index<self.count){
        return [self gel_objectAtIndex:index];
    }else{
        NSLog(@"数组已越界objectAtIndex = %ld  count = %ld", index, self.count);
        return nil;
    }
}

- (id)gel_randomObject {
    if (self.count) {
        return self[arc4random_uniform((u_int32_t)self.count)];
    }
    return nil;
}

- (NSString *)gel_jsonStringEncoded {
    if ([NSJSONSerialization isValidJSONObject:self]) {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:0 error:&error];
        NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        return json;
    }
    return nil;
}

- (NSString *)gel_jsonPrettyStringEncoded {
    if ([NSJSONSerialization isValidJSONObject:self]) {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        return json;
    }
    return nil;
}

@end
